﻿using System.Windows;
using HandyControl.Controls;
using IntoTheVoid.Views;
using Prism.Mvvm;
using Prism.Commands;
using System;
using System.Runtime.InteropServices;
using HandyControl.Tools.Extension;
using System.Windows.Threading;
using IntoTheVoid.State;
using IntoTheVoid.Units.DownloadEventArgs;
using System.IO;
using IntoTheVoid.Models;
using IntoTheVoid.Units;
using System.Diagnostics;
using System.Security.Policy;
using System.Windows.Shapes;
using System.Collections.Generic;
using IntoTheVoid.Properties;
using System.Windows.Markup;
using System.Windows.Media.Imaging;
using DryIoc;


namespace IntoTheVoid.ViewModels
{

	public partial class MainViewModel : BindableBase
	{
		[DllImportAttribute("User32.dll")]
		private static extern int FindWindow(String ClassName, String WindowName);

		[DllImport("user32.dll")]
		public static extern bool SetForegroundWindow(int hWnd);

		[DllImport("user32.dll")]
		private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
		public Dictionary<AdvertTabEnum, List<AdvertData>> advertDatas { get; set; }

		private MainView window;
		private string versionString = "";
		public string VersionString
		{
			get { return versionString; }
			set
			{
				versionString = value;
				RaisePropertyChanged();
			}
		}
		//下载信息1号位，左上
		private string downLoadInfo01 = "";
		public string DownLoadInfo01
		{
			get { return downLoadInfo01; }
			set
			{
				downLoadInfo01 = value;
				RaisePropertyChanged();
			}
		}

		//下载信息2号位，左下
		private string downLoadInfo02 = "";
		public string DownLoadInfo02
		{
			get { return downLoadInfo02; }
			set
			{
				downLoadInfo02 = value;
				RaisePropertyChanged();
			}
		}

		//下载信息3号位，右下
		public string downLoadInfo03 = "";
		public string DownLoadInfo03
		{
			get { return downLoadInfo03; }
			set { downLoadInfo03 = value; RaisePropertyChanged(); }
		}

		//百分比进度值
		public double downLoadPrecent;
		public double DownLoadPrecent
		{
			get { return downLoadPrecent; }
			set { downLoadPrecent = value; RaisePropertyChanged(); }
		}

		// 下载整块是否显示
		private Visibility progressShowMark = Visibility.Hidden;
		public Visibility ProgressShowMark
		{
			get { return progressShowMark; }
			set
			{
				progressShowMark = value;
				RaisePropertyChanged();
			}
		}

		//下载和暂停按钮切换
		private bool isDownPause = false;
		public bool IsDownPause
		{
			get { return isDownPause; }
			set { isDownPause = value; RaisePropertyChanged(); }
		}


		// 主按钮内容
		private string mainButtonContent = "";
		public string MainButtonContent
		{
			get { return mainButtonContent; }
			set { mainButtonContent = value; RaisePropertyChanged(); }
		}
		// 主按钮背景
		private string mainButtonBackground = "StartDownloadButton";
		public string MainButtonBackground
		{
			get { return mainButtonBackground; }
			set { mainButtonBackground = value; RaisePropertyChanged(); }
		}
		private Style mainButtonStyle;
		public Style MainButtonStyle
		{
			get { return mainButtonStyle; }
			set { mainButtonStyle = value; RaisePropertyChanged(); }
		}

		// 主按钮是否可以操作
		private bool mainButtonEnabled = true;
		public bool MainButtonEnabled
		{
			get { return mainButtonEnabled; }
			set { mainButtonEnabled = value; RaisePropertyChanged(); }
		}
		// 设置显示
		private Visibility mainSettingWindow = Visibility.Hidden;
		public Visibility MainSettingWindow
		{
			get { return mainSettingWindow; }
			set
			{
				mainSettingWindow = value;
				RaisePropertyChanged();
			}
		}

		private Visibility mainSettingButton = Visibility.Visible;
		public Visibility MainSettingButton
		{
			get { return mainSettingButton; }
			set
			{
				mainSettingButton = value;
				RaisePropertyChanged();
			}
		}

		private string content = "";
		public string Content
		{
			get { return content; }
			set { content = value; RaisePropertyChanged(); }
		}

		// 当前广告tab显示
		private AdvertTabEnum currentAdvertTabSet = AdvertTabEnum.activity;
		public AdvertTabEnum CurrentAdvertTabSet
		{
			get{ return currentAdvertTabSet; }
			set
			{ 
				currentAdvertTabSet = value;
				DealAdvertData();
				RaisePropertyChanged(); 
			}
		}

		private string advertShowTitle1 = "";
		public string AdvertShowTitle1
		{
			get { return advertShowTitle1; }
			set { advertShowTitle1 = value; RaisePropertyChanged(); }
		}

		private string advertShowTitle2 = "";
		public string AdvertShowTitle2
		{
			get { return advertShowTitle2; }
			set { advertShowTitle2 = value; RaisePropertyChanged(); }
		}
		private string advertShowTitleOrg1 = "";
		public string AdvertShowTitleOrg1
		{
			get { return advertShowTitleOrg1; }
			set { advertShowTitleOrg1 = value; RaisePropertyChanged(); }
		}

		private string advertShowTitleOrg2 = "";
		public string AdvertShowTitleOrg2
		{
			get { return advertShowTitleOrg2; }
			set { advertShowTitleOrg2 = value; RaisePropertyChanged(); }
		}
		private string advertShowTitleTime1 = "";
		public string AdvertShowTitleTime1
		{
			get { return advertShowTitleTime1; }
			set { advertShowTitleTime1 = value; RaisePropertyChanged(); }
		}

		private string advertShowTitleTime2 = "";
		public string AdvertShowTitleTime2
		{
			get { return advertShowTitleTime2; }
			set { advertShowTitleTime2 = value; RaisePropertyChanged(); }
		}
		private List<ImageData> currentListImg = null;
		public List<ImageData> CurrentListimg
		{
			set
			{
				currentListImg = value;
				RaisePropertyChanged();
			}
		}

		// 处理轮播图数据
		public void DealAdvertData()
		{
			AdvertShowTitle1 = "";
			AdvertShowTitleTime1 = "";
			AdvertShowTitle2 = "";
			AdvertShowTitleTime2 = "";
			AdvertShowTitleOrg1 = "";
			AdvertShowTitleOrg2 = "";
			if (advertDatas == null)
				return;

			if (!advertDatas.ContainsKey(currentAdvertTabSet)) 
			{ 
				return;
			}
			var datas = advertDatas[currentAdvertTabSet];


			if (datas.Count > 0)
			{
				AdvertShowTitle1 = DealOverTitleString(datas[0].title);
				AdvertShowTitleOrg1 = datas[0].title;
				AdvertShowTitleTime1 = datas[0].time;
			}
			if (datas.Count > 1)
			{
				AdvertShowTitle2 = DealOverTitleString(datas[1].title);
				AdvertShowTitleOrg2 = datas[1].title;
				AdvertShowTitleTime2 = datas[1].time;
			}
		}
		public string DealOverTitleString(string title)
		{
			if(title.Length > 26) 
			{
				title = title.Substring(0,26);
				title += "...";
			}
			return title;
		}
		public DelegateCommand ConfirmCommond { get; private set; }
		public DelegateCommand OpenSetingViewCommand { get; private set; }
		public DelegateCommand OpenGameClickCommand { get; private set; }
		public DelegateCommand GameSetClickCommand { get; private set; }
		// public DelegateCommand StopDownGameClickCommand { get; private set; }
		public DelegateCommand ShowDownloadPathClickCommand { get; private set; }
		public DelegateCommand CheckGameUpdateClickCommand { get; private set; }
		public DelegateCommand CheckFileClickCommand { get; private set; }
		public DelegateCommand PreDownLoadClickCommand { get; private set; }

		public DelegateCommand AdvertOpenClickCommand1 { get; private set; }
		public DelegateCommand AdvertOpenClickCommand2 { get; private set; }

		private string _errorMessage;

		// 下载状态数据
		public static StateContext stateContext;

		public MainViewModel(MainView window)
		{
			this.window = window;
			VersionString = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
			OpenSetingViewCommand = new DelegateCommand(OpenSettingWindowClick);
			OpenGameClickCommand = new DelegateCommand(OpenGameClick);
			GameSetClickCommand = new DelegateCommand(MainGameSetClick);
			// StopDownGameClickCommand = new DelegateCommand(StopDownGameClick);
			ConfirmCommond = new DelegateCommand(() => this.window.WindowClose());
			ShowDownloadPathClickCommand = new DelegateCommand(ShowDownloadClick);
			CheckGameUpdateClickCommand = new DelegateCommand(CheckGameUpdateClick);
			CheckFileClickCommand = new DelegateCommand(CheckFileClick);
			PreDownLoadClickCommand = new DelegateCommand(PreDownLoadClick);
			// 下载器状态
			stateContext = new StateContext();
			stateContext.CurState = new FirstCheckState(stateContext, true);
			stateContext.ButtonStateArgs += CurState_StateArgs;
			stateContext.ProcessStateArgs += CurState_ProcessStateArgs;
			stateContext.TipsArgs += CurState_TipsArgs;
			stateContext.WindowStateArgs += CurState_WindowStateArgs;
			stateContext.ShowInstallPathChangeView += StateContext_ShowInstallPathChangeView;
			// 进入后直接进行检查
			stateContext.CurState.Start(stateContext);
			InitializeTimer();
			AdvertOpenClickCommand1 = new DelegateCommand(AdvertOpenClick1);
			AdvertOpenClickCommand2 = new DelegateCommand(AdvertOpenClick2);

			// 指定样式文件的路径
			var myResourceDictionary = new ResourceDictionary
			{
				Source = new Uri("/Resource/ButtonStyle.xaml", UriKind.RelativeOrAbsolute) 
			};
			// 通过key找到指定的样式
			MainButtonStyle = myResourceDictionary["StartDownloadButton"] as Style;

			AdvertDataManager.SendAdvertConfig();
			AdvertDataManager.DownLoadAdvertConfigCompleted += DownLoadAdvertConfigCompleted;

			// 初始化上报
			Common.InitializeCrash();


		}
		private void DownLoadAdvertConfigCompleted(object sender, GameDownloadConfigEventArgs e)
		{
			if (e.Code != 0)
				return;
			// 轮播图数据
			List<AdvertData> datas = AdvertDataManager.jsonData.adverts;
			if (datas != null && datas.Count > 0)
			{
				advertDatas = new Dictionary<AdvertTabEnum, List<AdvertData>>();
				foreach (var data in datas)
				{
					if (!advertDatas.ContainsKey(data.type))
					{
						advertDatas.Add(data.type, new List<AdvertData>());
					}
					advertDatas[data.type].Add(data);
				}
			}
			// 轮播图图片位置
			var pic = AdvertDataManager.jsonData.pictures;
			if (pic != null)
			{
				List<ImageData> imgList = new List<ImageData>();
				foreach (var img in pic)
				{
					ImageData imageData = new ImageData();
					imageData.bitmap = new BitmapImage(new Uri(img.pic_url, UriKind.Absolute));
					imageData.link = img.link;
					imgList.Add(imageData);
				}
				window.AdvertPic.CurrentListimg = imgList;
			}
			currentAdvertTabSet = AdvertTabEnum.activity;
			DealAdvertData();
			RaisePropertyChanged();
		}
		private void OpenSettingWindowClick()
		{
			var view = new SettingView();
			var dialog = Dialog.Show(view);
			var settingViewModel = (dialog.Content as SettingView).DataContext as SettingViewModel;
			settingViewModel.ChangeDownloadSpeed += ChangeDownloadSpeed;
			settingViewModel.DeleteGameInfoFiles += ClearGamePathFile;
			settingViewModel.ParentDialog = dialog;
			if (stateContext.StateType == StateType.Downloading || stateContext.StateType == StateType.Installing
			|| stateContext.StateType == StateType.Opening || stateContext.StateType == StateType.Updating
			|| stateContext.StateType == StateType.DownloadingStop)
			{
				settingViewModel.IIsChangeDownloadFilterEnable = false;
			}
			if (stateContext.StateType == StateType.Downloading || stateContext.StateType == StateType.Installing
			|| stateContext.StateType == StateType.Opening || stateContext.StateType == StateType.Updating)
			{
				settingViewModel.IIsClearGameFileEnable = false;
			}
			//dialog.Content = tipView;
			MainSettingWindow = Visibility.Hidden;
		}
		private void StateContext_ShowInstallPathChangeView(object sender, EventArgs e)
		{
			App.Current.Dispatcher.Invoke((Action)(() =>
			{
				var view = new InstallPathChangeView();
				var dialog = Dialog.Show(view);
				var viewModel = (dialog.Content as InstallPathChangeView).DataContext as InstallPathChangeViewModel;
				viewModel.ParentDialog = dialog;
			}));
		}

		private void ClearGamePathFile(object sender, EventArgs e)
		{
			ShowTips("这个操作会清理当前游戏文件夹所有内容，\n请确认游戏文件夹没有其他文件，\n清理后需要重新下载整体游戏，\n是否继续操作", () => {
				LogHelper.Info("ClearGamePathFile");
				Common.ClearAllFiles();
				IsDownPause = false;
				// BaseInfoContentModel.Instance.SetValue("gameInstallPath", targetPath);
				stateContext.CurState = new FirstCheckState(stateContext);
				stateContext.CurState.Start(stateContext);
				ShowTips("操作完成");
			}, null);
		}
		// 更新限速
		private void ChangeDownloadSpeed(object sender, DownloadSpeedChangetArgs e)
		{
			var speed = -1;
			if (e.Unlimited)
			{
				speed = e.LimitSpeed;
			}
			if (stateContext.CurState is DownloadState)
			{
				DownloadState state = (DownloadState)stateContext.CurState;
				state.downloadController?.SetSpeed(speed * 1000);
			}

		}
		// 窗口显示
		private void CurState_WindowStateArgs(object sender, MainWindowVisableArgs e)
		{
			if (window != null)
			{
				if (e.Show)
				{
					window.Show();
				}
				else
				{
					window.Hide();
				}
				window.WindowState = e.State;
			}
		}
		// 显示提示
		private void CurState_TipsArgs(object sender, TipsEventArgs e)
		{
			//Content = e.Content;
			ShowTips(e.Content, e.ConfirmAction, e.CancelAction);
			MainSettingWindow = Visibility.Hidden;
		}
		private void ShowTips(string content, Action confirmAction = null, Action cancelAction = null)
		{
			App.Current.Dispatcher.Invoke((Action)(() =>
			{
				var view = new TipView(content, confirmAction, cancelAction);
				var dialog = Dialog.Show(view);
				var viewModel = (dialog.Content as TipView).DataContext as TipViewModel;
				viewModel.ParentDialog = dialog;
			}));
		}
		// 进度条信息
		private void CurState_ProcessStateArgs(object sender, ProcessStateChangeEventArgs e)
		{
			DownLoadInfo01 = e.DownloadInfo1;
			DownLoadInfo02 = e.DownloadInfo2;
			DownLoadInfo03 = e.DownloadInfo3;
			DownLoadPrecent = e.Percent;
		}
		ResourceDictionary myResourceDictionary = null;
		// 按钮数据
		private void CurState_StateArgs(object sender, ButtonStateChangeEventArgs e)
		{
			MainButtonContent = e.MainButtonContent;
			if (e.MainButtonBackground != "")
			{
				MainButtonBackground = e.MainButtonBackground;
				if(myResourceDictionary == null)
				{
					// 指定样式文件的路径
					myResourceDictionary = new ResourceDictionary
					{
						Source = new Uri("/Resource/ButtonStyle.xaml", UriKind.RelativeOrAbsolute)
					};
				}
				// 通过key找到指定的样式
				MainButtonStyle = myResourceDictionary[mainButtonBackground] as Style;
			}


			MainButtonEnabled = e.MainButtonEnabled;
			if (e.ShowPercent)
			{
				ProgressShowMark = Visibility.Visible;
			}
			else
			{
				ProgressShowMark = Visibility.Hidden;
			}

			if (e.ShowSettingButton)
			{
				MainSettingButton = Visibility.Visible;
			}
			else
			{
				MainSettingButton = Visibility.Hidden;
			}

		}
		// 暂停、恢复下载
		// private void StopDownGameClick()
		// {
		// 	if (!IsDownPause)
		// 	{
		// 		stateContext.CurState.Pause(stateContext);
		// 	}
		// 	else
		// 	{
		// 		stateContext.CurState.Start(stateContext);
		// 	}
		// 	IsDownPause = !IsDownPause;
		// 	MainSettingWindow = Visibility.Hidden;
		// }

		// 开始按钮
		public void OpenGameClick()
		{
			stateContext.CurState.Start(stateContext);
			MainSettingWindow = Visibility.Hidden;
		}
		public void MainGameSetClick()
		{
			if(MainSettingWindow == Visibility.Hidden)
			{
				MainSettingWindow = Visibility.Visible;
			}
			else
			{
				MainSettingWindow = Visibility.Hidden;
			}
		}
		public void ShowDownloadClick()
		{
			App.Current.Dispatcher.Invoke((Action)(() =>
			{
				var view = new InstallPathChangeView();
				var dialog = Dialog.Show(view);
				var viewModel = (dialog.Content as InstallPathChangeView).DataContext as InstallPathChangeViewModel;
				viewModel.ParentDialog = dialog;
			}));
			// 显示下载文件夹
/*			var basePath = AppDomain.CurrentDomain.BaseDirectory;
			var defaultPath = Path.Combine(basePath, "Game");
			var path = BaseInfoContentModel.Instance.GetValue<string>("gameInstallPath", defaultPath);

			if (!Directory.Exists(path))
			{
				try
				{
					Directory.CreateDirectory(path);
				}
				catch (Exception e)
				{
					LogHelper.Error("Logs Filter Create Error" + e.Message);
				}
			}
			Process.Start(path);
*/			MainSettingWindow = Visibility.Hidden;
		}
		public void CheckGameUpdateClick()
		{
			stateContext.CurState = new FirstCheckState(stateContext, true, true);
			stateContext.CurState.Start(stateContext);
			MainSettingWindow = Visibility.Hidden;
		}

		public void CheckFileClick()
		{
			MainSettingWindow = Visibility.Hidden;
			if (stateContext.StateType == StateType.NeedDownload || 
				stateContext.StateType == StateType.Downloading  ||
				stateContext.StateType == StateType.DownloadingStop)
			{
				ShowTips("请先下载游戏");
			}
			else if (stateContext.StateType == StateType.Updating ||
				stateContext.StateType == StateType.NeedUpdate)
			{ 
				ShowTips("请先更新游戏");
			}
			else if (stateContext.StateType == StateType.Opening)
			{
				ShowTips("请先关闭游戏");
			}
			else if(stateContext.StateType == StateType.CanOpenGame)
			{
				var defaultPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Game");
				var targetPath = BaseInfoContentModel.Instance.GetValue<string>("gameInstallPath", defaultPath);
				var zipDiffInfoJsonName = System.IO.Path.Combine(targetPath, "IntoTheVoid", "diff_info.json");
				stateContext.CurState = new FileCheckState(stateContext, zipDiffInfoJsonName);
			}
			MainSettingWindow = Visibility.Hidden;
		}
		public void PreDownLoadClick()
		{
			MainSettingWindow = Visibility.Hidden;

			if (stateContext.StateType == StateType.CanOpenGame)
				stateContext.CurState = new PreDownloadState(stateContext);
			else if (stateContext.StateType == StateType.NeedDownload )
				ShowTips("请先下载游戏");
			else if(stateContext.StateType == StateType.NeedUpdate)
				ShowTips("请先更新游戏");
			else
				ShowTips("当前状态无法进行预下载");

		}

		public void AdvertOpenClick1()
		{
			if (!advertDatas.ContainsKey(currentAdvertTabSet))
				return;
			var datas = advertDatas[currentAdvertTabSet];
			if(datas != null)
			{
				var link = datas[0].link;
				if(link != null)
					System.Diagnostics.Process.Start(link);
			}
		}
		public void AdvertOpenClick2()
		{
			if (!advertDatas.ContainsKey(currentAdvertTabSet))
				return;
			var datas = advertDatas[currentAdvertTabSet];
			if (datas.Count > 1)
			{
				var link = datas[1].link;
				if (link != null)
					System.Diagnostics.Process.Start(link);
			}
		}
		private DispatcherTimer timer;

		private void InitializeTimer()
		{
			// 定时更新事件
			this.timer = new DispatcherTimer();
			this.timer.Interval = new TimeSpan(hours: 1, minutes: 0, seconds: 0);
			this.timer.Tick += Timer_Tick;
			timer.Start();
		}

		// 开始定时器
		public void Start()
		{
			timer.Start();
		}

		// 停止定时器
		public void Stop()
		{
			timer.Stop();
		}

		// 定时器 Tick 事件处理程序
		private void Timer_Tick(object sender, EventArgs e)
		{
			// 在这里执行更新检查的逻辑
			CheckForUpdates();
		}

		private void CheckForUpdates()
		{
			if (stateContext.StateType == StateType.Downloading || 
				stateContext.StateType == StateType.Updating || 
				stateContext.StateType == StateType.Opening)
				return;
			LogHelper.Info("Timer Check For Update");
			stateContext.CurState = new FirstCheckState(stateContext, true);
			stateContext.CurState.Start(stateContext);
		}
		

	}


}
